<template>
  <div class="el-select" @click.stop="toggleMenu" ref="sel">
    <div class="el-input el-input--suffix">
      <input  v-model="labelTxt" type="text" readonly="readonly" autocomplete="off" :placeholder="placeholder" class="el-input__inner">
      <span class="el-input__suffix">
        <span class="el-input__suffix-inner">
          <i class="el-select__caret el-input__icon el-icon-arrow-up"></i>
        </span>
      </span>
    </div>
    <transition name="el-zoom-in-top">
      <div ref="content" class="el-select-dropdown el-popper" v-show="visible" style="z-index: 2000;">
        <div class="el-scrollbar">
          <div class="el-select-dropdown__wrap el-scrollbar__wrap" style="margin-bottom: -17px; margin-right: -17px;">
            <ul class="el-scrollbar__view el-select-dropdown__list">
              <li class="el-select-dropdown__item" :class="selected == item[val] ? 'selected' : ''"
              v-for="(item, index) in options" :key="index" :value="item[val]">
                {{ item[currentLabel]}}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>
<script>
import utils from '@/assets/utils'
export default {
  props: {
    value: {
      required: true // 选中的值
    },
    val: {
      required: true // value 对应的key
    },
    name: [String, Number],
    placeholder: {
      type: String,
      default: '请选择'
    },
    options: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      selected: '',
      visible: false,
      labelTxt: ''
    }
  },
  watch: {
    selected (val) {
      this.callabel()
      this.$emit('input', val)
    }
  },
  computed: {
    currentLabel () {
      return this.name ? this.name : this.val
    }
  },
  methods: {
    toggleMenu () {
      (this.visible && this.hide()) || this.show()
    },
    show () {
      this.visible = true
      utils.addEvent(document, 'click', this.hide, true)
    },
    hide (e) {
      this.visible = false
      if (this.$refs.sel && this.$refs.sel.contains(e.target)) {
        // 如果是子元素则阻止事件捕获
        utils.stopEvent(e)
        this.setVal(e.target)
      }
      utils.removeEvent(document, 'click', this.hide, true)
    },
    setVal (item) {
      this.selected = item.value
      this.$emit('change', item.value)
    },
    callabel () {
      if (this.selected) {
        this.options.forEach(item => {
          if (item[this.val] === this.selected) {
            this.labelTxt = item[this.currentLabel]
          }
        })
      } else {
        this.labelTxt = ''
      }
    }
  },
  mounted () {
    this.selected = this.value
  }
}
</script>
<style lang="scss" scoped>
.el-select{
  display: inline-block;
  position: relative;
  .el-popper{
    width: 100%;
  }
}
.el-select-dropdown__item.hover, .el-select-dropdown__item:hover {
  background-color: #f5f7fa;
}
</style>
